#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# author: kamon
# Created on 2021
# lastupdate 2022-8-26
# 服务进程监测，用于进程异常中断自动启动或重启

import os
import sys
import time

# 项目根目录
rootDir = '/data/www/hyperf_project1/'
# 进程名称(APP_NAME)
progressName = 'hyperf_project1'
# 运行用户
runUser = 'www'
# 运行环境
php = '/usr/bin/php'
composer = '/usr/local/bin/composer'


# 获取进程PID
def getPids():
    commandRes = os.popen("ps -x | grep -E '%s\\.[a-zA-Z]+.*' | grep -v grep | gawk -F' ' '{ print $1 }'" % progressName).read().strip().split("\n")
    return " ".join(commandRes).strip()


# 启动进程
def launch():
    print(os.popen('cd {} && {} dump-autoload -o'.format(rootDir, composer)).read().strip())
    print(os.popen('cd {} && {} -dmemory_limit=-1 bin/hyperf.php start > /dev/null 2>&1'.format(rootDir, php)).read().strip())
    print(os.popen('sleep 1 && ps -xf | grep {} | grep -v grep'.format(progressName)).read().strip())


# 开始(监控/启动)
def start():
    currentUser = os.popen('/usr/bin/whoami').read().strip()
    if currentUser != runUser:
        print('只允许用“{}”账号运行进程！'.format(runUser))
        exit()
    progressNum = int(os.popen('ps -x | grep -E "%s\\.Master|%s\\.Manager" | grep -v grep | wc -l' % (progressName, progressName)).read().strip())
    if progressNum == 0:  # 正常启动
        launch()
        print("%s 服务进程已启动..." % progressName)
    elif progressNum == 1:  # 进程异常重启
        progressIds = getPids()
        if progressIds != '':
            os.popen('kill -9 {} > /dev/null 2>&1'.format(progressIds))
        time.sleep(1)
        launch()
        print("%s 服务进程已重新启动..." % progressName)
    else:
        print("%s 服务进程运行中..." % progressName)


# 停止进程
def stop():
    progressIds = getPids()
    if progressIds != '':
        os.popen('kill -9 {} > /dev/null 2>&1'.format(progressIds))
        print("%s 已结束所有进程！！！" % progressName)
    else:
        print("%s 没有启动的进程！！！" % progressName)


if __name__ == '__main__':
    if len(sys.argv) > 1 and sys.argv[1].strip() == 'stop':
        stop()
    elif len(sys.argv) > 1 and sys.argv[1].strip() == 'start':
        start()
    elif len(sys.argv) > 1 and sys.argv[1].strip() == 'restart':
        stop()
        time.sleep(1)
        start()
    else:
        start()
